package com.shark.security.jwt.controller;

import java.text.ParseException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.shark.security.jwt.constant.MessageCode;
import com.shark.security.jwt.constant.RedisConstant;
import com.shark.security.jwt.domain.JsonResponse;
import com.shark.security.jwt.security.model.LoginUser;
import com.shark.security.jwt.service.AuthService;
import com.shark.security.jwt.service.CodeService;
import com.shark.security.jwt.utils.RedisUtil;

@RestController
public class HelloController {

    @Value("${jwt.header}")
    private String tokenHeader;

    @Autowired
    private AuthService authService;

    @Autowired
    private CodeService codeService;

    @PreAuthorize("hasAuthority('hello:test')")
    @RequestMapping("/hello")
    public String hello() {
        return "Hello";
    }
    @RequestMapping("/hello2")
    public String hello2() {
        return "Hello2";
    }


    @RequestMapping("/code")
    public String code() throws ParseException {
        final String tbl = "TEST_TB";
        final String col = "TEST_COL";
        final Date d = DateUtils.parseDate(DateFormatUtils.format(new Date(), "yyyyMMdd"), "yyyyMMdd");
        return codeService.generateCode(tbl,col, d);
    }

    @RequestMapping(value = "${jwt.route.authentication.path}")
    public JsonResponse<String> createAuthenticationToken(LoginUser loginUser)
            throws AuthenticationException {
        final String token = authService.login(loginUser);
        RedisUtil.set(RedisConstant.User_Login_Token + loginUser.getUsername(), token, 36000);
        return JsonResponse.success(token);
    }

    @RequestMapping(value = "${jwt.route.authentication.refresh}", method = RequestMethod.GET)
    public JsonResponse<String> refreshAndGetAuthenticationToken(
            HttpServletRequest request) throws AuthenticationException {
        String token = request.getHeader(tokenHeader);
        String refreshedToken = authService.refresh(token);
        if (refreshedToken == null) {
            return JsonResponse.error(MessageCode.Token_Refresh_Failed);
        } else {
            return JsonResponse.success(refreshedToken);
        }
    }
}
